package com.dimples.system.service.impl;

import com.dimples.common.entity.SecurityUser;
import com.dimples.common.service.DimplesJwtTokenServiceImpl;
import com.dimples.common.util.HttpContextUtil;
import com.dimples.system.entity.SysUserOnline;
import com.dimples.system.service.UserOnlineService;

import org.springframework.stereotype.Service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/8/9
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserOnlineServiceImpl implements UserOnlineService {

    private final DimplesJwtTokenServiceImpl tokenService;

    @Override
    public SysUserOnline selectOnlineByUserName(String userName, SecurityUser user) {
        if (StrUtil.equals(userName, user.getUsername())) {
            return loginUserToUserOnline(user);
        }
        return null;
    }

    @Override
    public SysUserOnline loginUserToUserOnline(SecurityUser user) {
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }
        SysUserOnline sysUserOnline = new SysUserOnline();
        sysUserOnline.setCurrent(StrUtil.equals(tokenService.getUsernameFromToken(HttpContextUtil.getRequest()), user.getUsername()));
        sysUserOnline.setTokenId(user.getLoginDetails().getTokenId());
        sysUserOnline.setUsername(user.getUsername());
        sysUserOnline.setIpaddr(user.getLoginDetails().getIpAddr());
        sysUserOnline.setLoginLocation(user.getLoginDetails().getLocation());
        sysUserOnline.setBrowser(user.getLoginDetails().getBrowser());
        sysUserOnline.setOs(user.getLoginDetails().getOs());
        sysUserOnline.setLoginTime(user.getLoginTime());
        sysUserOnline.setDeptName(user.getDeptName());
        return sysUserOnline;
    }

    @Override
    public void removeOnlineUser(String tokenId) {
        tokenService.removeToken(tokenId);
    }
}
